package com.guazai.project.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.*;
import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guazai.common.pojo.User;
import com.guazai.project.common.DeleteRequest;
import com.guazai.project.common.ErrorCode;
import com.guazai.project.constant.UserConstant;
import com.guazai.project.exception.BusinessException;
import com.guazai.project.mapper.UserMapper;
import com.guazai.project.model.dto.user.*;
import com.guazai.project.model.vo.LoginUserVO;
import com.guazai.project.model.vo.UserVO;
import com.guazai.project.model.vo.UserVoucherVO;
import com.guazai.project.service.UserService;
import com.guazai.project.utils.AbsolutePathUtils;
import com.guazai.project.utils.EmailUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import static com.guazai.project.constant.UserConstant.*;


/**
 * @author guazai
 * @description 用户服务实现类
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {

    /**
     * 注入图片存储地址
     */
    @Value("${guazai-api.upload.avatarLocalPath}")
    private String avatarLocalPath;

    /**
     * 主机地址
     */
    @Value("${guazai-api.host}")
    private String apiHost;

    @Resource
    private UserMapper userMapper;

    @Resource
    EmailUtils emailUtils;

    /**
     * 盐值，混淆密码
     */
    private static final String SALT = "guazai";

    /**
     * 用户注册
     *
     * @param userAccount   用户账户
     * @param userPassword  用户密码
     * @param checkPassword 校验密码
     * @return
     */
    @Override
    public long userRegister(String userAccount, String userPassword, String checkPassword) {
        // 1. 校验
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        if (userAccount.length() < 2) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户账号过短");
        }
        if (userPassword.length() < 8 || checkPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户密码过短");
        }
        // 密码和校验密码相同
        if (!userPassword.equals(checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "两次输入的密码不一致");
        }
        synchronized (userAccount.intern()) {
            // 账户不能重复
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("userAccount", userAccount);
            long count = userMapper.selectCount(queryWrapper);
            if (count > 0) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号重复");
            }
            // 2. 加密
            String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
            // 3. 插入数据
            String secretId = generateSecretId(userAccount);
            String secretKey = generateSecretKey(userAccount);
            User user = new User();
            user.setUserAccount(userAccount);
            user.setUserPassword(encryptPassword);
            user.setUserAvatar(apiHost + DEFAULT_USER_AVATAR);
            user.setUserName("guazaiApi_" + userAccount);
            user.setSecretId(secretId);
            user.setAccessKey(userAccount);
            user.setSecretKey(secretKey);
            user.setUserProfile(DEFAULT_USER_PROFILE);
            boolean saveResult = this.save(user);
            if (!saveResult) {
                throw new BusinessException(ErrorCode.SYSTEM_ERROR, "注册失败，数据库错误");
            }
            // 返回id
            return user.getId();
        }
    }

    /**
     * 添加用户
     *
     * @param user
     * @return
     */
    @Override
    public long addUser(User user) {
        String userAccount = user.getUserAccount();
        synchronized (userAccount.intern()) {
            // 账户不能重复
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("userAccount", userAccount);
            long count = userMapper.selectCount(queryWrapper);
            if (count > 0) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号重复");
            }
            // 2. 加密
            String userPassword = user.getUserPassword();
            String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
            // 3. 插入数据
            user.setUserPassword(encryptPassword);
            boolean saveResult = this.save(user);
            if (!saveResult) {
                throw new BusinessException(ErrorCode.SYSTEM_ERROR, "注册失败，数据库错误");
            }
            return user.getId();
        }
    }

    /**
     * 用户登录
     *
     * @param userAccount  用户账户
     * @param userPassword 用户密码
     * @param request
     * @return
     */
    @Override
    public User userLogin(String userAccount, String userPassword, HttpServletRequest request) {
        // 1. 校验
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        if (userAccount.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号错误");
        }
        if (userPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码错误");
        }
        // 2. 加密
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
        // 查询用户是否存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount);
        queryWrapper.eq("userPassword", encryptPassword);
        User user = userMapper.selectOne(queryWrapper);
        // 用户不存在
        if (user == null) {
            log.info("user login failed, userAccount cannot match userPassword");
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户不存在或密码错误");
        }
        // 3. 记录用户的登录态
        request.getSession().setAttribute(UserConstant.USER_LOGIN_STATE + user.getId(), user);
        return user;
    }

    /**
     * 获取当前登录用户
     *
     * @param request
     * @return
     */
    @Override
    public User getLoginUser(HttpServletRequest request) {
        // 先判断是否已登录
        String authorization = request.getHeader("Authorization");
        HttpSession session = request.getSession();
        Object userObj = session.getAttribute(UserConstant.USER_LOGIN_STATE + authorization);
        User currentUser = (User) userObj;
        if (currentUser == null || currentUser.getId() == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        // 从数据库查询（追求性能的话可以注释，直接走缓存）
        long userId = currentUser.getId();
        currentUser = this.getById(userId);
        if (currentUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        return currentUser;
    }

    /**
     * 是否为管理员
     *
     * @param request
     * @return
     */
    @Override
    public boolean isAdmin(HttpServletRequest request) {
        // 仅管理员可查询
        String authorization = request.getHeader("Authorization");
        Object userObj = request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE + authorization);
        User user = (User) userObj;
        return user != null && UserConstant.ADMIN_ROLE.equals(user.getUserRole());
    }

    /**
     * 用户注销
     *
     * @param request
     */
    @Override
    public boolean userLogout(HttpServletRequest request) {
        //获取id
        String authorization = request.getHeader("Authorization");
        if (request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE + authorization) == null) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "未登录");
        }
        // 移除登录态
        request.getSession().removeAttribute(UserConstant.USER_LOGIN_STATE + authorization);
        return true;
    }

    /**
     * 分页查询用户并以VO对象返回
     *
     * @param request
     * @return
     */
    public Page<UserVO> listUserVOByPage(UserQueryRequest request) {
        //限制爬虫
        if (request.getPageSize() > 20) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //分页查询条件封装
        Page<User> page = new Page<>(request.getCurrent(), request.getPageSize());
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.like(StringUtils.isNotBlank(request.getUserName()), "userName", request.getUserName());
        wrapper.like(StringUtils.isNotBlank(request.getUserProfile()), "userProfile", request.getUserProfile());
        wrapper.eq(StringUtils.isNotBlank(request.getUserRole()), "userRole", request.getUserRole());
        //查询
        userMapper.selectPage(page, wrapper);
        List<User> records = page.getRecords();
        //如果查询结果为空，则返回一个空记录的Page<UserVO>
        Page<UserVO> userVOPage = new Page<>(request.getCurrent(), request.getPageSize());
        if (CollectionUtils.isEmpty(records)) {
            userVOPage.setRecords(new ArrayList<>());
            return userVOPage;
        }
        //把结果映射成UserVO
        List<UserVO> result = records.stream().map(this::getUserVO).collect(Collectors.toList());
        userVOPage.setRecords(result);
        //返回userVOPage
        return userVOPage;
    }

    /**
     * 将user转为userVO
     *
     * @param user
     * @return
     */
    public UserVO getUserVO(User user) {
        if (user == null) {
            return null;
        }

        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        return userVO;
    }

    /**
     * 获取凭证
     *
     * @param request
     * @return
     */
    @Override
    public User getVoucher(HttpServletRequest request) {
        // 获取当前登录用户
        User loginUser = this.getLoginUser(request);
        // 是否登录
        if (ObjUtil.isEmpty(loginUser)) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        // 获取凭证
        User user = this.getById(loginUser.getId());
        return user;
    }

    /**
     * 修改用户并删除头像
     *
     * @param userUpdateRequest
     * @return
     */
    @Override
    public boolean updateUser(UserUpdateRequest userUpdateRequest) {
        //判断要修改的用户是否存在
        User userInDB = this.getById(userUpdateRequest.getId());
        if (ObjUtil.isEmpty(userInDB)) {
            log.error("要修改的用户不存在!");
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "要修改的用户不存在");
        }

        //拷贝属性并修改
        User user = new User();
        BeanUtils.copyProperties(userUpdateRequest, user);

        //删除头像
        String userAvatarInRequest = user.getUserAvatar();
        String defaultAvatarUrl = apiHost + "/" + DEFAULT_USER_AVATAR;

        //三种情况不用删
        String userAvatarInDB = userInDB.getUserAvatar();
        if (StringUtils.isBlank(userAvatarInDB) || defaultAvatarUrl.equals(userAvatarInRequest) || userAvatarInRequest.equals(userAvatarInDB)) {
            log.info("无需删除头像");
        } else {
            deleteAvatar(userAvatarInDB);
        }

        //修改数据库数据
        boolean flag = this.updateById(user);
        if (!flag) {
            log.info("用户修改失败！");
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "用户修改失败！");
        }

        return true;
    }

    /**
     * 删除用户
     *
     * @param deleteRequest
     * @return
     */
    @Override
    public boolean removeUser(DeleteRequest deleteRequest) {
        //判断要删除的用户是否存在
        User userInDB = this.getById(deleteRequest.getId());
        if (ObjUtil.isEmpty(userInDB)) {
            log.error("要删除的用户不存在!");
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "要删除的用户不存在");
        }

        //拷贝属性并修改
        User user = new User();
        BeanUtils.copyProperties(deleteRequest, user);

        //删除头像
        String userAvatarInRequest = user.getUserAvatar();
        String defaultAvatarUrl = apiHost + "/" + DEFAULT_USER_AVATAR;

        //三种情况不用删
        String userAvatarInDB = userInDB.getUserAvatar();
        if (StringUtils.isBlank(userAvatarInDB) || defaultAvatarUrl.equals(userAvatarInRequest) || userAvatarInRequest.equals(userAvatarInDB)) {
            log.info("无需删除头像");
        } else {
            deleteAvatar(userAvatarInDB);
        }

        boolean b = this.removeById(user.getId());
        if (!b) {
            log.info("删除失败");
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "删除失败");
        }

        log.info("删除成功！{}", b);
        return b;
    }

    /**
     * 删除头像
     *
     * @param avatarUrl
     */
    private void deleteAvatar(String avatarUrl) {
        //获取头像连接的URL对象
        URL url = null;
        try {
            url = new URL(avatarUrl);
        } catch (MalformedURLException e) {
            throw new RuntimeException(e);
        }
        //通过正则表达式提取name参数值
        Pattern pattern = Pattern.compile("name=([^&]+)");
        Matcher matcher = pattern.matcher(url.getQuery());
        if (!matcher.find()) {
            log.info("头像路径参数格式错误！路径参数为：{}", url.getQuery());
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "头像路径参数格式错误！");
        }
        String name = matcher.group(1);
        //获得绝对路径
        String absolutePath = AbsolutePathUtils.getAbsolutePath(avatarLocalPath);
        String filePath = absolutePath + name;
        boolean del = FileUtil.del(filePath);
        if (!del) {
            log.info("头像删除失败");
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "头像删除失败");
        }
    }

    /**
     * 删除用户（多个id）
     *
     * @param deleteListRequest
     * @param request
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean deleteUserByIds(DeleteListRequest deleteListRequest, HttpServletRequest request) {
        if (deleteListRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = this.getLoginUser(request);
        List<Long> ids = deleteListRequest.getIds();
        // 判断是否存在
        List<User> users = this.listByIds(ids);
        if (users.size() != ids.size()) {
            List<Long> idsInDB = users.stream().map(User::getId).collect(Collectors.toList());
            List<Long> differentIds = CollUtil.disjunction(ids, idsInDB).stream().collect(Collectors.toList());
            log.error("differentIds:{}", differentIds);
            if (differentIds.size() > 0) {
                throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "未找到删除数据：differentIds：" + differentIds);
            }
        }
        // 校验是否为管理员
        if (!this.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "只允许管理员删除");
        }
        boolean removeByIdsFlag = this.removeByIds(ids);
        if (!removeByIdsFlag) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }
        return true;
    }

    /**
     * 修改用户密码
     * @param userUpdatePasswordRequest
     * @param id
     * @return
     */
    @Override
    public boolean updatePassword(UserUpdatePasswordRequest userUpdatePasswordRequest, Long id) {
        String oldPassword = userUpdatePasswordRequest.getOldPassword();
        String newPassword = userUpdatePasswordRequest.getNewPassword();
        String checkNewPassword = userUpdatePasswordRequest.getCheckNewPassword();
        if(StrUtil.isBlank(oldPassword)||StrUtil.isBlank(newPassword) || StrUtil.isBlank(checkNewPassword)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        if(oldPassword.equals(newPassword)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "新密码不能与旧密码相同");
        }
        if(!newPassword.equals(checkNewPassword)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "两次输入的新密码不一致");
        }
        User user = this.getById(id);
        if(!DigestUtils.md5DigestAsHex((SALT + oldPassword).getBytes()).equals(user.getUserPassword())){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "旧密码错误！！！");
        }
        User userUpdate = new User();
        userUpdate.setId(id);
        userUpdate.setUserPassword(DigestUtils.md5DigestAsHex((SALT + newPassword).getBytes()));
        return this.updateById(userUpdate);
    }

    @Override
    public boolean updateUserName(User user) {
        Long id = user.getId();
        String userName = user.getUserName();
        if(ObjectUtil.isEmpty(id) || StrUtil.isBlank(userName)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean update = this.updateById(user);
        if(!update){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "修改昵称失败，请稍后再试");
        }
        return true;
    }

    @Override
    public Boolean sendCodeEmail(String to, HttpServletRequest request) {
        if (StringUtils.isBlank(to) || request == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        HttpSession session = request.getSession();
        String attribute = (String) session.getAttribute(UserConstant.EMAIL_CODE_KEY_PREFIX + to);

        if (!StringUtils.isBlank(attribute)) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "验证码已发送，请十分钟后再试");
        }

        String result = emailUtils.sendCodeEmail(to);
        if (StringUtils.isBlank(result)) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "发送验证码失败");
        }
        session.setAttribute(EMAIL_CODE_KEY_PREFIX + to, result);

        return true;
    }

    @Override
    public LoginUserVO userLoginByEmail(UserLoginByEmailRequest userLoginByEmailRequest, HttpServletRequest request) {
        String code = userLoginByEmailRequest.getVerificationCode();
        String email = userLoginByEmailRequest.getEmail();
        if (userLoginByEmailRequest == null
                || StringUtils.isAnyBlank(code, email)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "邮箱或验证码为空");
        }

        if (code.length() != UserConstant.VERIFICATION_CODE_LENGTH) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "验证码错误");
        }

        HttpSession session = request.getSession();
        checkCode(code, email, request);

        //查询用户是否存在
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("email", email);
        User userDB = this.getOne(wrapper);
        LoginUserVO loginUserVO = new LoginUserVO();
        if (userDB != null) {
            BeanUtils.copyProperties(userDB, loginUserVO);
            return loginUserVO;
        }
        //用户不存在则注册用户
        String randowmAccount = DEFAULT_ACCOUNT_PREFIX + IdUtil.fastSimpleUUID();
        String secretId = generateSecretId(randowmAccount);
        String secretKey = generateSecretKey(randowmAccount);

        User user = new User();
        String passowrdMD5 = DigestUtils.md5DigestAsHex((SALT + DEFAULT_PASSWORD).getBytes());
        user.setUserAccount(randowmAccount);
        user.setUserPassword(passowrdMD5);
        user.setUserAvatar(apiHost + DEFAULT_USER_AVATAR);
        user.setEmail(email);
        user.setUserRole(DEFAULT_ROLE);
        user.setUserName(DEFAULT_USER_NAME);
        user.setSecretId(secretId);
        user.setSecretKey(secretKey);
        user.setUserProfile(DEFAULT_USER_PROFILE);

        int insert = userMapper.insert(user);
        if (insert == 0) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "自动注册用户失败");
        }

        session.setAttribute(UserConstant.USER_LOGIN_STATE, user);

        BeanUtils.copyProperties(user, loginUserVO);
        return loginUserVO;
    }


    @Override
    public Boolean bindEmail(UserBindEmailRequest userBindEmailRequest, HttpServletRequest request) {
        User loginUser = this.getLoginUser(request);
        // 是否登录
        if(ObjUtil.isEmpty(loginUser)){
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        //判断email是否为空
        String email = userBindEmailRequest.getEmail();
        if (StringUtils.isBlank(email)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //判断该邮箱是否已经被绑定了
        QueryWrapper wrapper = new QueryWrapper<>();
        wrapper.eq("email", email);
        User userDB = this.getOne(wrapper);
        if (userDB != null) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "邮箱已经被绑定");
        }


        //判断验证码是否正确
        String code = userBindEmailRequest.getVerificationCode();
        checkCode(code, email, request);
        //移除session的验证码
        HttpSession session = request.getSession();
        session.removeAttribute(EMAIL_CODE_KEY_PREFIX + email);

        //修改user
        User user = new User();
        user.setId(loginUser.getId());
        user.setEmail(email);
        return this.updateById(user);
    }

    @Override
    public Boolean unBindEmail(HttpServletRequest request) {
        User loginUser = this.getLoginUser(request);
        // 是否登录
        if(ObjUtil.isEmpty(loginUser)){
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }

        UpdateWrapper wrapper = new UpdateWrapper<>();
        wrapper.eq("id", loginUser.getId());
        wrapper.set("email", null);
        return this.update(wrapper);

    }

    @Override
    public UserVoucherVO updateVoucher(HttpServletRequest request) {
        //判断是否登录并拿到登录用户信息
        User loginUser = getLoginUser(request);
        //更新secretKey和secretId
        String secretKey = generateSecretKey(loginUser.getUserAccount());
        String secretId = generateSecretId(loginUser.getUserAccount());
        //修改数据库数据
        User user = new User();
        user.setId(loginUser.getId());
        user.setSecretKey(secretKey);
        user.setSecretId(secretId);
        log.info("更新秘钥：{}", user);
        boolean flag = this.updateById(user);
        //如果修改失败则抛出异常
        if (!flag) {
            log.error("更新秘钥失败");
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "更新秘钥失败");
        }
        //修改成功则返回新的secretKey和secretId
        UserVoucherVO vo = BeanUtil.copyProperties(user, UserVoucherVO.class);
        return vo;
    }

    private static void checkCode(String code, String email, HttpServletRequest request) {
        //判断验证码
        HttpSession session = request.getSession();
        String attribute = (String) session.getAttribute(UserConstant.EMAIL_CODE_KEY_PREFIX + email);
        if (StringUtils.isBlank(attribute)) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }

        if (!code.equals(attribute)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "验证码错误");
        }
        //验证码正确，移除session中的验证码
        session.removeAttribute(EMAIL_CODE_KEY_PREFIX + email);
    }

    /**
     * 生成secretId
     */
    private String generateSecretId(String userAccount) {
        String secretId = DigestUtil.md5Hex(SALT + userAccount + RandomUtil.randomString(8));
        return secretId;
    }

    /**
     * 生成secretKey
     */
    private String generateSecretKey(String userAccount) {
        String secretKey = DigestUtil.md5Hex(SALT + userAccount + RandomUtil.randomString(8));
        return secretKey;
    }


}




